package com.ccb.sc.github.yydzxz.miniprogram.api.impl;

import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.json.WxMaGsonBuilder;
import cn.binarywang.wx.miniapp.util.crypt.WxMaCryptUtils;
import com.ccb.sc.github.yydzxz.common.util.UrlUtil;
import com.ccb.sc.github.yydzxz.miniprogram.api.IByteDanceMiniProgramLoginService;
import com.ccb.sc.github.yydzxz.miniprogram.api.IByteDanceMiniProgramService;
import com.ccb.sc.github.yydzxz.miniprogram.api.impl.request.login.Code2sessionRequest;
import com.ccb.sc.github.yydzxz.miniprogram.api.impl.response.login.Code2sessionResponse;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.json.GsonParser;
import org.apache.commons.codec.digest.DigestUtils;

import static cn.binarywang.wx.miniapp.constant.WxMaApiUrlConstants.User.GET_PHONE_NUMBER_URL;

/**
 * @author yangyidian
 * @date 2021/09/02
 **/
@Slf4j
public class ByteDanceMiniProgramLoginServiceImpl implements IByteDanceMiniProgramLoginService {

    private IByteDanceMiniProgramService byteDanceMiniProgramService;

    public ByteDanceMiniProgramLoginServiceImpl(IByteDanceMiniProgramService byteDanceMiniProgramService) {
        this.byteDanceMiniProgramService = byteDanceMiniProgramService;
    }

    @Override
    public Code2sessionResponse code2session(Code2sessionRequest request) {
        String url = UrlUtil.buildUrl(CODE_2_SESSION_URL, request);
        return byteDanceMiniProgramService.get(url, Code2sessionResponse.class);
    }

    @Override
    public Code2sessionResponse code2session(String code, String anonymousCode) {
        AbstractByteDanceMiniProgramInRedisConfigStorage.MiniProgramInfo config =
                byteDanceMiniProgramService.getMiniProgramConfig();
        Code2sessionRequest request = new Code2sessionRequest();
        request.setCode(code);
        request.setAnonymousCode(anonymousCode);
        request.setAppid(config.getAppId());
        request.setSecret(config.getAppSecret());
        return this.code2session(request);
    }

    @Override
    public WxMaUserInfo getUserInfo(String sessionKey, String encryptedData, String ivStr) {
        return WxMaUserInfo.fromJson(WxMaCryptUtils.decrypt(sessionKey, encryptedData, ivStr));
    }

    @Override
    public boolean checkUserInfo(String sessionKey, String rawData, String signature) {
        final String generatedSignature = DigestUtils.sha1Hex(rawData + sessionKey);
        return generatedSignature.equals(signature);
    }

    @Override
    public WxMaPhoneNumberInfo getPhoneNoInfo(String sessionKey, String encryptedData, String ivStr) {
        return WxMaPhoneNumberInfo.fromJson(WxMaCryptUtils.decrypt(sessionKey, encryptedData, ivStr));
    }

}
